package com.yuns.config;

import com.yuns.common.utils.CookieUtils;
import com.yuns.common.utils.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token拦截器
 *
 * @author liuchengwen
 * @Date 2020-11-18
 */
public class Interceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 查询token
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token) || "".equals(token) || "undefined".equals(token)) {
            // 未登录,无需处理
            return true;
        }
        try {
            // 判断是否过期
            boolean cache = TokenUtils.verify(token);
            if (!cache) {
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            }
            return true;
        } catch (Exception e) {
            // 抛出异常，证明未登录,返回401
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }
}
